package com.agent.user.comsumer;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.agent.commons.constants.RedisConstants.*;

@Component
@Slf4j
public class CodeComsumer {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "code.queue"),
            exchange = @Exchange(name = "direct.exchange", type = ExchangeTypes.DIRECT),
            key = {"code","picture"},
            arguments = @Argument(name = "x-delay", value = "lazy")
    ))
    public void directMessage(Map<String, Object>  message) {
        log.info("消费者1接收到direct.queue消息：{}", message);
        if(message.get("url")!=null&&message.get("code")!=null){
            log.info("图片验证码保存!");
            stringRedisTemplate.opsForValue().set(PICTURE_CODE+message.get("code"),  JSONUtil.toJsonStr(message.get("url")));
        }else {
            stringRedisTemplate.opsForValue().set(REGISTER_LOGIN_CODE + message.get("email"), JSONUtil.toJsonStr(message.get("code")), LOGIN_CODE_TIME, TimeUnit.MINUTES);
        }
    }

    /**
     * 生成token令牌
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value ="token.queue"),
            exchange = @Exchange(name = "direct.exchange", type = ExchangeTypes.DIRECT),
            key = {"token"},
            arguments = @Argument(name = "x-delay", value = "lazy")
    ))
    public void generateToken(Map<String, Object> message) {
        log.info("消费者1接收到direct.queue消息：{}", message);
        //存入redis中，过期时限为1小时
        stringRedisTemplate.opsForValue().set(TOKEN + message.get("userId"), (String) message.get("token"), LOGIN_CODE_TIME, TimeUnit.HOURS);
    }
}
